package com.ijunfu.webSocket;

import com.ijunfu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @Title  : 监听websocket
 * @Author : ijunfu <ijunfu@163.com>
 * @Date   : 2024/2/6 10:45
 * @Version: 1.0
 * @Motto  : 简洁的代码是智慧的结晶 卓越的编码是对复杂性的优雅征服
 *
 */
@Slf4j
@Component
@ServerEndpoint(value = "/ws/{uid}", encoders = { WsEncoder.class })
@EnableScheduling
public class WsServerEndpoint {

    private final static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid) {

        sessionPool.remove(uid);
        sessionPool.put(uid, session);

        log.info("[{}]websocket连接成功", uid);
    }

    @OnMessage
    public R onMessage(String message, @PathParam("uid") String uid) {
        log.info("[{}] 收到了一条信息: {}", uid, message);

        return R.ok();
    }

    @OnClose
    public void onClose(Session session, @PathParam("uid") String uid) {

        sessionPool.remove(uid);

        log.warn("[{}] websocket is closed.", uid);
    }

    /**
     * @Title  : 心跳检测 - 每隔2秒向客户端发送心跳
     * @Param	:
     * @Return : void
     * @Author : ijunfu <ijunfu@163.com>
     * @Date   : 2024/2/6 22:51
     * @Motto  : 简洁的代码是智慧的结晶 卓越的编码是对复杂性的优雅征服
     */
    @Scheduled(fixedDelay = 2000)
    public void sendMsg() {
        for(Session session : sessionPool.values()) {
            try {
                session.getBasicRemote().sendText("hello");
            } catch (Exception e) {
                log.error("发送消息失败", e);
            }
        }
    }
}
